package io.github.fb513.transport;

import com.rabbitmq.client.ConnectionFactory;
import io.github.fb513.common.constant.RabbitConstants;
import io.github.fb513.common.util.IpUtils;
import io.github.fb513.transport.command.CommandChain;
import io.github.fb513.transport.command.LoginCommand;
import io.github.fb513.transport.config.BootstrapConfig;
import io.github.fb513.transport.config.ImConfig;
import io.github.fb513.transport.exception.InitServiceException;
import io.github.fb513.transport.queue.MessageQueueReceiver;
import io.github.fb513.transport.queue.MessageQueueSender;
import io.github.fb513.transport.queue.MessageQueueServer;
import io.github.fb513.transport.registry.ConsulRegistry;
import io.github.fb513.transport.server.WebSocketServer;
import org.yaml.snakeyaml.Yaml;

public class Main {
    public static void main(String[] args) {
        Yaml yaml = new Yaml();
        BootstrapConfig bootstrapConfig = yaml.loadAs(Main.class.getClassLoader().getResourceAsStream("config.yml"), BootstrapConfig.class);
        ImConfig imConfig = bootstrapConfig.getIm();
        if (imConfig.getIpAddress() == null || imConfig.getIpAddress().isEmpty()) {
            String host = IpUtils.getIP(imConfig.getIpPrefix());
            if (host == null || host.isEmpty()) {
                throw new InitServiceException("can not get ip address");
            }
            imConfig.setIpAddress(host);
        }
        imConfig.setIpNum(IpUtils.ipToLong(imConfig.getIpAddress()));

        MessageQueueServer mqServer = new MessageQueueServer(bootstrapConfig.getRabbitmq());
        ConnectionFactory connectionFactory = mqServer.getConnectionFactory();
        MessageQueueSender messageSender = new MessageQueueSender(bootstrapConfig, connectionFactory);
        MessageQueueReceiver messageReceiver = new MessageQueueReceiver(RabbitConstants.web_to_im_message,
                bootstrapConfig, mqServer.getConnectionFactory());
        messageReceiver.listen();

        CommandChain commandChain = new CommandChain(messageSender);
        commandChain.add(new LoginCommand(commandChain, imConfig));

        new WebSocketServer(bootstrapConfig, commandChain).start();

        new ConsulRegistry(bootstrapConfig).serviceRegister();
    }
}